package org.example.laboratorymanagement.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.pojo.Result;
import org.example.laboratorymanagement.pojo.Student;
import org.example.laboratorymanagement.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@Slf4j
@RequestMapping("/students")
@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     *
     * @return
     */
    @GetMapping
    public Result listStudents(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               String username, String name, String lesson) {
        log.info("分页查询学生，参数：{},{},{},{},{}",page,pageSize,username,name,lesson);

        PageBean pageBean = studentService.pageStudents(page, pageSize, username, name, lesson);

        return Result.success(pageBean);
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        log.info("批量删除学生ID操作，ids：{}",ids);
        studentService.delete(ids);
        return Result.success();

    }

    @PutMapping
    public Result update(@RequestBody Student student){
        log.info("修改学生：{}",student);

        studentService.update(student);
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody Student student){
        log.info("学生登录：{}",student);
        Student s = studentService.login(student);

        if (s!=null){
            return Result.success(s);
        }

        return Result.error("学生：用户名或密码错误");

    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id){
        log.info("获取学生ID：{}", id);
        Student s = studentService.selectctById(id);
        return Result.success(s);
    }

    @PostMapping
    public Result add(@RequestBody Student student){
        log.info("新增学生：{}",student);
        studentService.add(student);
        return Result.success();
    }

    @PostMapping("/insertBatch")
    public Result insertBatch(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Student> students = reader.readAll(Student.class);
        log.info("批量添加学生：{}",students);
        try {
            studentService.insertBatch(students);
        } catch (Exception e) {
            return Result.error("数据库批量导入出错！");
        }

        return Result.success();
    }

}
